<?php

namespace app\admin\controller\pt;

use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\controller\Backend;
use app\admin\model\pt\PlanMonth as MonthModel;
use app\admin\model\pt\PlanRange as RangeModel;
use app\common\library\Plan as PlanLib;

/**
 * 部门管理
 *
 * @icon fa fa-circle-o
 */
class Depart extends Backend
{

    /**
     * Depart模型对象
     * @var \app\admin\model\pt\Depart
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pt\Depart;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function year($ids)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $model = new MonthModel();
            $limit = 1000;
            $list = $model
                ->where('pt_depart_id', $ids)
                ->order('year_id', 'desc')
                ->order('month_id', 'asc')
                ->paginate($limit);
            
            // 查找出所有数据后进行按年份分组
            $rows = $list->items();
            $newData = [];
            foreach ($rows as $r) {
                $newData[$r['year_id']][] = $r->toArray();
            }

            $data = [];
            foreach ($newData as $yearId => $nd) {
                $tmp = [
                    'year'  => $yearId . "年",
                    'year_id' => $yearId,
                ];
                $totalfee = 0;
                foreach ($nd as $n) {
                    $totalfee += $n['fee_total'];
                    $str = "费用:" . $n['fee_total'];
                    $str .= "<br />兼职人次:" . $n['parttime_total'];
                    $str .= "<br />实习生人次:" . $n['intern_total'];
                    $str .= "<br />总人次:" . ($n['parttime_total'] + $n['intern_total']);
                    $tmp['month_' . $n['month_id']] = $str;
                }
                $tmp['total_fee'] = $totalfee;
                $data[] = $tmp;
            }


            $result = array("total" => $list->total(), "rows" => $data);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function yearAdd($ids)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $departId = $params['pt_depart_id'];
                $yearId = $params['year_id'];
                $months = $params['months'];
                if (empty($departId) || empty($yearId) || empty($months)) {
                    $this->error('参数不完整');
                }
                $months = json_decode($months, true);
                $result = false;
                Db::startTrans();
                try {
                    $planLib = new PlanLib();    
                    $planLib->handleMonthPlan($months, $yearId, $departId);
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 构造json字符串
        $months = [];
        for ($m = 1; $m <= 12; $m++) {
            $month = [
                "month_id" => $m,
                "month" => $m . "月",
                "fee_total" => '',
                "parttime_total" => '',
                "intern_total" => '',
            ];
            $months[] = $month;
        }
        $row = [];
        $row['months'] = json_encode($months);
        $row['pt_depart_id'] = $ids;
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    public function yearEdit($departId = null, $ids = null)
    {
        $count = MonthModel::where('pt_depart_id', $departId)->where('year_id', $ids)->count();
        if (!$count) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $departId = $params['pt_depart_id'];
                $yearId = $params['year_id'];
                $months = $params['months'];
                if (empty($departId) || empty($yearId) || empty($months)) {
                    $this->error('参数不完整');
                }
                $months = json_decode($months, true);
                $result = false;
                Db::startTrans();
                try {
                    $planLib = new PlanLib();    
                    $planLib->handleMonthPlan($months, $yearId, $departId);
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 查找数据
        $data = MonthModel::where('pt_depart_id', $departId)->where('year_id', $ids)->select();
        $row = [];
        $months = [];
        foreach ($data as $d) {
            $month = [
                "month_id" => $d->month_id,
                "month" => $d->month_id . "月",
                "fee_total" => $d->fee_total,
                "parttime_total" => $d->parttime_total,
                "intern_total" => $d->intern_total,
            ];
            $months[] = $month;
        }
        $row = [];
        $row['months'] = json_encode($months);
        $row['pt_depart_id'] = $departId;
        $row['year_id'] = $ids;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function range($ids)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $model = new RangeModel();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $model
                ->where($where)
                ->where('pt_depart_id', $ids)
                ->order('start_date_id', 'asc')
                ->paginate($limit);
            
            // 查找出所有数据后进行按年份分组
            $rows = $list->items();
            $newData = [];
            foreach ($rows as $r) {
                $tmp = $r->toArray();
                $dateStr = date('Y-m-d',strtotime($tmp['start_date_id'])) . "到" . date('Y-m-d', strtotime($tmp['end_date_id']));
                $tmp['date_str'] = $dateStr;
                $newData[] = $tmp;
            }

            $result = array("total" => $list->total(), "rows" => $newData);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function rangeAdd($ids)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $departId = $params['pt_depart_id'];
                $startDate = $params['start_date_id'];
                $endDate = $params['end_date_id'];
                $planTotal = $params['plan_total'];
                if (empty($departId) || empty($planTotal) || empty($startDate) || empty($endDate)) {
                    $this->error('参数不完整');
                }
                $result = false;
                Db::startTrans();
                try {
                    $planLib = new PlanLib();    
                    $planLib->handleRangePlan($startDate, $endDate, $departId, $planTotal);
                    $planLib->calDepartPlan($startDate, $endDate, $departId);
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('depart_id', $ids);
        return $this->view->fetch();
    }

    public function rangeEdit($ids = null)
    {
        $row = RangeModel::get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $departId = $params['pt_depart_id'];
                $startDate = $params['start_date_id'];
                $endDate = $params['end_date_id'];
                $planTotal = $params['plan_total'];
                if (empty($planTotal) || empty($startDate) || empty($endDate)) {
                    $this->error('参数不完整');
                }
                $result = false;
                Db::startTrans();
                try {
                    $planLib = new PlanLib();    
                    $planLib->handleRangePlan($startDate, $endDate, $departId, $planTotal, $ids);
                    $planLib->calDepartPlan($startDate, $endDate, $departId, $ids);
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
